﻿using Blog.Model.Dto.Memento;
using Blog.Model.Entitys;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blog.Service
{
    public class MementoService : IMementoService
    {
        private ISqlSugarClient _db;
        public MementoService(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ApiResult AddMemento(MementoAdd model)
        {
            var data = new Memento()
            {
                Title = model.Title,
                DebrisContent = model.DebrisContent,
                CoverImg = model.CoverImg,
                IsShow = model.IsShow,
                TagId = model.TagId,
            };

            var msg = _db.Insertable(data).ExecuteCommand() >= 1 ? "提交成功":"提交失败";

            return new ApiResult().OK(msg);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult DelMemento(ListIds param)
        {
            var ids = param.ids;

            //真删除
            //int number = _db.Deleteable<Memento>().In(ids).ExecuteCommand();

            //修改状态，目前用的表达式更新
            int number = _db.Updateable<Memento>().SetColumns(m => m.IsDelete == true)
                .Where(m => ids.Contains(m.Id)).ExecuteCommand();

            return new ApiResult().OK($"成功删除{number}条记忆碎片");

        }

        /// <summary>
        /// 显示
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public ApiResult MementoList(ListParam param)
        {
            int page = param.Take();
            int size = param.Skip();
            int totalCount = 0;

            var data = _db.Queryable<Memento>().Where(m => m.IsShow && !m.IsDelete).ToPageList(page,size,ref totalCount);

            return new ApiResult().OK(data, totalCount);
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult UpMemento(MementoUp param)
        {
            bool isUp = _db.Updateable<Memento>().SetColumns(m => new Memento { Title = param.Title,
                IsShow = param.IsShow, DebrisContent  = param.DebrisContent,
                CoverImg = param.CoverImg,
                TagId = param.TagId,
            })
                .Where(m => m.Id == param.Id).ExecuteCommandHasChange();
            string msg = isUp ? "编辑成功" : "编辑失败";
            return new ApiResult().OK(msg);
        }
    }
}
